<script lang="ts">
  import { CreateDatasetParamSchema, type Dataset, DatasetFactory, Visibility, canAddDataset$} from "@store/entity/dataset";
  import EntityModal from "@component/modals/EntityModal.svelte"; 
  import { RadioButton, RadioList } from "@component/radio/index";
  import { create, update } from "@service/dataset";
  import { alertError } from "@store/global";

  let _errors: Record<string, string> = {};
  let _dataset: Dataset = DatasetFactory(undefined, "", Visibility.Public, "");
  
  let hidden = true;
  $: isNew = !_dataset.id
  $: confirmButtonText = isNew ? "创建" : "更新";
  $: title = `${confirmButtonText}数据集`;

  export const show = async (dataset?: Dataset) => {
    if (dataset) {
      _dataset = {...dataset}
    } else {
      _dataset = DatasetFactory(undefined, "", Visibility.Public, "");
    }

    console.log('_dataset=>', _dataset)  
    _errors = {};
    hidden = false;
  }
  async function onModalConfirm () {
    if (isNew && !$canAddDataset$) {
      alertError('can not add apps reach maxinum !!')
      return
    }
    try {
      console.log("before validate!")
      await CreateDatasetParamSchema.validate(_dataset, { abortEarly: false });
      _errors = {};
      console.log('after validate success')
      if (isNew) {
        await create(_dataset)
      } else {
        await update(_dataset)
      }
      hidden = true
    } catch (err: any) {
      console.error(' validate err=>', err)
      if (err.inner) {
        _errors = err.inner.reduce((acc, err) => {
          return { ...acc, [err.path]: err.message };
        }, {});
      }
      hidden = false;
    }
  }
</script>
<EntityModal bind:hidden={hidden} {title} {confirmButtonText} on:modal-confirm={onModalConfirm} >
  <div class="flex-field">
      <label for="name" class="modal-label flex-start-box">名称*</label>
      <input type="text" name="name" id="name" bind:value={_dataset.name} class="modal-input" placeholder="最多10个字" required />
      <div class="flex-start-box h-12" ><span class="error" class:hidden={!_errors.name}>{_errors.name}</span></div>
  </div>
  <div class="flex-field">
    <label for="name" class="modal-label flex-start-box">可见性*</label>
    <RadioList bind:value={_dataset.vis}>
      {#each Object.values(Visibility) as item}
        <RadioButton opt="{item}" disabled={!isNew} ></RadioButton>
      {/each}
    </RadioList>
    <div class="flex-start-box h-12" ><span class="error" class:hidden={!_errors.name}>{_errors.name}</span></div>
</div>
  <div class="flex-field" >
      <label for="desc" class="modal-label flex-start-box">描述</label>
      <textarea rows="2" name="desc" id="desc" bind:value={_dataset.desc} class="modal-input" placeholder="20个字以内" />
      <div class="flex-start-box h-12" ><span class="error" class:hidden={!_errors.desc}>{_errors.desc}</span></div>
  </div>
  <div/>
</EntityModal>